<template>
  <div>
    <el-card style="margin-top: 30px;">
      <el-button type="primary" icon="el-icon-plus" @click="showDialog">
        添加
      </el-button>

      <el-table
        :data="trademark"
        border
        style="margin-top: 20px;"
        v-loading="loading"
      >
        <el-table-column
          type="index"
          label="序号"
          width="80px"
        ></el-table-column>

        <el-table-column label="品牌名称" prop="tmName"> </el-table-column>

        <el-table-column label="品牌LOGO">
          <template slot-scope="scope">
            <el-image :src="scope.row.logoUrl" style="width: 100px;" />
          </template>
        </el-table-column>

        <el-table-column label="操作">
          <template slot-scope="slot">
            <el-button
              icon="el-icon-edit"
              type="warning"
              @click="changeTrademark(slot.row)"
            ></el-button>
            <el-button
              icon="el-icon-delete"
              type="danger"
              @click="removeTrademark(slot.row.id)"
            ></el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        :total="total"
        :page-size.sync="size"
        :current-page.sync="current"
        :page-sizes="[5, 10, 15]"
        layout="total, prev, pager, next,->, jumper,sizes"
      ></el-pagination>
    </el-card>

    <el-dialog
      :title="formDate.id ? '修改品牌' : '添加品牌'"
      :visible.sync="dialogVisible"
      width="80%"
      @close="closeHandler"
    >
      <el-form ref="formDate" :model="formDate" label-width="100px">
        <el-form-item
          label="品牌名称"
          prop="tmName"
          :rules="{
            required: true,
            min: 1,
            message: '品牌名称必填',
            trigger: 'blur'
          }"
        >
          <el-input
            v-model="formDate.tmName"
            placeholder="请输入名牌名称"
          ></el-input>
        </el-form-item>

        <el-form-item
          label="品牌LOGO"
          prop="logoUrl"
          :rules="{
            required: true,
            message: '必须上传图片',
            trigger: 'blur'
          }"
        >
          <el-upload
            class="avatar-uploader"
            action="http://gmall-h5-api.atguigu.cn/admin/product/upload"
            :show-file-list="false"
            :on-success="onSeccessHandler"
            :before-upload="beforeUpdata"
          >
            <img
              v-if="formDate.logoUrl"
              :src="formDate.logoUrl"
              style="width:178px;height:178px"
            />
            <el-icon v-else class="el-icon-plus avatar-uploader-icon"
              ><ele-Plus></ele-Plus
            ></el-icon>

            <div slot="tip" class="el-upload__tip">
              只能上传jpg/png文件，且不超过2M
            </div>
          </el-upload>
        </el-form-item>
      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="addTrademark" v-loading="btnLoading"
          >确 定</el-button
        >
        <el-button @click="dialogVisible = false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import * as tradapis from "@/api/trad";
export default {
  name: "trademark",
  data() {
    return {
      trademark: [],
      total: 0, //总页数
      size: 5, //每页多少条
      current: 1, //当前页
      pages: 0, //总页数
      dialogVisible: false,
      formDate: {
        tmName: "",
        logoUrl: ""
      },
      loading: false,
      btnLoading: false
    };
  },
  mounted() {
    this.getPagination();
  },
  methods: {
    /* 获取分页数据 */
    async getPagination() {
      try {
        this.loading = true;
        const res = await tradapis.reqPagination(this.current, this.size);
        const { current, pages, size, total, records } = res.data;
        this.trademark = records;
        this.total = total;
        this.pages = pages;
        this.current = current;
        this.size = size;
      } catch (e) {
        this.$message.error("获取名牌列表失败");
      } finally {
        this.loading = false;
      }
    },

    /* 点击按钮切换dialog */
    showDialog() {
      this.dialogVisible = true;
      if (this.formDate.id) {
        this.formDate = {
          tmName: "",
          logoUrl: ""
        };
      }
    },

    //上传成功
    onSeccessHandler(res) {
      this.formDate.logoUrl = res.data;
    },

    //上传之前
    beforeUpdata(file) {
      const imgRules = file.type === "image/jpeg" || file.type === "image/png";
      const isSize2M = file.size / 1024 / 1024 < 2;

      if (!imgRules) {
        this.$message.error("上传图片格式只能是jpg和png");
      }
      if (!isSize2M) {
        this.$message.error("上传头像图片大小不能超过 2MB!");
      }
      return imgRules && isSize2M;
    },
    /* 当dialog关闭 */
    closeHandler() {
      this.$refs.formDate.clearValidate();
    },

    /* 提交/修改品牌 */
    async addTrademark() {
      let fg = this.formDate.id ? "修改" : "添加";
      try {
        this.btnLoading = true;
        await this.$refs.formDate.validate();

        if (this.formDate.id) {
          await tradapis.reqChangeTrademark(this.formDate);
        } else {
          await tradapis.reqAddTrademark(this.formDate);
        }

        if (this.total % this.size === 0) {
          console.log("1111");
          this.current = this.pages + 1;
        } else {
          this.current = this.pages;
          console.log("2222111");
        }
        this.$message.success(fg + "成功");
        this.dialogVisible = false;
        this.getPagination();
      } catch (e) {
        this.$message.error(fg + "失败");
      } finally {
        this.btnLoading = false;
      }
    },

    /* 修改品牌数据 */
    changeTrademark(data) {
      this.dialogVisible = true;
      this.formDate = { ...data };
    },

    /* 删除品牌数据 */
    async removeTrademark(id) {
      try {
        await this.$confirm("确定要删除吗？", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        });
        await tradapis.reqRemoveTrademark(id);
        this.$message.success("删除成功");
        if (this.trademark.length === 1) {
          this.current = this.pages - 1;
        }
        this.getPagination();
      } catch (e) {
        if (e != "cancel") {
          this.$message.error("删除失败");
        }
      }
    }
  },
  watch: {
    current() {
      this.getPagination();
    },
    size() {
      this.getPagination();
    }
  }
};
</script>

<style>
.avatar-uploader .el-upload {
  width: 178px;
  height: 178px;
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>
